package ru.weho.osmwidget;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.util.Log;

public class OSMBitmap {
	private static final String TAG = "OSMBitmap";
	private Location location;
	private int zoom;
	private float density;
	private String maptype;

	private static final int widgetSideDP = 146;

	OSMBitmap(Location location, int zoom, float density, String maptype) {
		this.location = location;
		this.zoom = zoom;
		this.density = density;
		this.maptype = maptype;
	}

	public Bitmap loadRemoteBitmap() {
		Bitmap bitmap = null;
		try {
			double longitude = location.getLongitude();
			double latitude = location.getLatitude();

			int widgetSide = (int) (widgetSideDP * density + 0.5f);
			String reqString = "http://staticmap.openstreetmap.de/staticmap.php?center=" + latitude + "," + longitude + "&zoom=" + zoom + "&size=" + (int)(widgetSide * 1.3) + "x" + (int)(widgetSide * 2) + "&maptype=" + maptype;
			Log.d(TAG, "Request string: " + reqString);
		    URL url = new URL(reqString);

		    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
		}
		catch (Exception e) {
		    Log.d(TAG, "Caught exception while getting remote bitmap: " + e);
		}
		return bitmap;
	}
}
